# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

library(gplots)
library(Hmisc)
library(optparse)
library(dplyr)
library(ropls)
library(magrittr)
library(tibble)
library(tidyr)
library(RFmarkerDetector)
library(scales)

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
    select(c("SampleID", "ClassNote")) %>%
    as.data.frame()

samples <- sampleInfo$SampleID
samples

classNotes <- unique(sampleInfo$ClassNote)

allData <- read.csv(opt$i, header = T, stringsAsFactors = F) %>%
    select(- c("HMDB", "KEGG", "Class")) %>%
    select(c("Metabolite", samples)) %>%
    rowwise() %>%
    do({
        result <- as.data.frame(.)
        for (group in classNotes) {
            sampleIds <- sampleInfo %>%
                filter(ClassNote == group) %>%
                .$SampleID
            groupData <- result[sampleIds] %>%
            unlist()
            mean <- mean(groupData)
            result[, paste0(group, ".Mean")] <- mean
            result[, paste0(group, ".SD")] = sd(groupData)
            median <- median(groupData)
            result[, paste0(group, ".Median")] <- median
            iqr11 <- quantile(groupData, 0.25)
            iqr12 <- quantile(groupData, 0.75)
            iqr1 <- paste0("[", iqr11, ",", iqr12, "]")
            result[, paste0(group, ".IQR")] <- iqr1
            result[, paste0(group, ".Min")] <- min(groupData)
            result[, paste0(group, ".Max")] <- max(groupData)
        }
        result
    }) %>%
    select(- c(samples))

head(allData)

parent <- "./"
fileName <- paste0(parent, "Basic_Statistics.csv")
data <- allData
write.csv(data, fileName, row.names = F)


